#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    tcpsocket=NULL;
    ui->setupUi(this);
    ui->pushButton_send->setEnabled(false);
    ui->pushButton_stop->setEnabled(false);
    ui->textEdit_ip->setText(ip);
    ui->textEdit_port->setText(port);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_link_clicked()
{
    tcpsocket=new QTcpSocket;

    ip=ui->textEdit_ip->toPlainText();
    port=ui->textEdit_port->toPlainText();
    if(ip.isEmpty()||port.isEmpty())
    {
        QMessageBox::information(this,"警告","请确定ip地址和端口号正确");
        return;
    }
    tcpsocket->connectToHost(ip,port.toUInt());

    connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(read_data()));
    connect(tcpsocket,SIGNAL(connected()),this,SLOT(connect_suc()));
    connect(tcpsocket,SIGNAL(disconnected()),this,SLOT(client_dis()));


}

void MainWindow::on_pushButton_stop_clicked()
{
    ui->pushButton_send->setEnabled(false);
    ui->pushButton_stop->setEnabled(false);
    ui->pushButton_link->setEnabled(true);
    tcpsocket->close();
    delete tcpsocket;

}


void MainWindow::read_data()
{
    QString msg=tcpsocket->readAll();
    ui->textEdit_get->setText(msg);
}

void MainWindow::on_pushButton_send_clicked()
{
    QString msg=ui->textEdit_send->toPlainText();
    tcpsocket->write(msg.toUtf8());

}

void MainWindow::connect_suc()
{
    ui->pushButton_send->setEnabled(true);
    ui->pushButton_stop->setEnabled(true);
    ui->pushButton_link->setEnabled(false);
}

void MainWindow::client_dis()
{
    QMessageBox::information(this,"警告","断开连接");
    ui->pushButton_send->setEnabled(false);
    ui->pushButton_stop->setEnabled(false);
    ui->pushButton_link->setEnabled(true);
}

